/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.seari.line17.handler;

import java.util.HashMap;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.seari.bean.Line17.Line17DataBean;
import com.seari.line17.Line17Client;
import com.seari.pa.handler.PaClientHandler;
import com.seari.utils.DataUtil;
import com.seari.utils.JedisPoolUtils;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import redis.clients.jedis.Jedis;

/**
 *
 * @author Rainbow
 */
public class Line17Handler extends ChannelInboundHandlerAdapter {

	protected static Logger logger = LoggerFactory.getLogger(Line17Handler.class);
	Line17Client client;
	Jedis jedis = JedisPoolUtils.getJedis();

	public Line17Handler() {
		super();
	}

	public Line17Handler(Line17Client client) {
		this.client = client;
	}

	@Override
	public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
		Line17DataBean result = (Line17DataBean) msg;
		String sysId = result.getSysID();
		int startAddress = result.getStartAddress(); 
		int packageNo = result.getPackageNo();
		int msgID = result.getMsgID();
		byte[] con = result.getContent();
		String str = "line17_";
		Map<String, String> map = new HashMap<String, String>();
		if (msgID == 1) {
                        startAddress = startAddress * 8; //根据期安协议文档修改，DI起始地址需要乘8
			str = str + "DI";
			for (int i = 0; i < con.length; i++) {
				for (int j = 0; j < 8; j++) {
					map.put(String.valueOf(startAddress), String.valueOf((con[i] >> j) & 0x1));
					startAddress++;
				}
			}
		} else if (msgID == 3) {
			str = str + "AI";
			for (int i = 0; i < con.length / 2; i ++) {
				map.put(String.valueOf(startAddress + i),
						String.valueOf(DataUtil.getHighLowByteValue(con[i * 2 + 1], con[i * 2])));
			}
		}
                logger.info("MSG ID:"+ msgID +"; start addr:" + startAddress + "; content:" + map.toString());
		jedis.hmset(str, map);
	}

	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception
	{
		closeJedis();
	}

	public void closeJedis()
	{
		if (null != jedis)
		{
			jedis.disconnect();
			jedis.close();
		}
	}


}
